<template>
  <div>
    <vc-drawings
      ref="drawings"
      position="bottom-right"
      :offset="[10, 40]"
      :editable="true"
      :clamp-to-ground="true"
      @draw-evt="handleDrawingDraw"
      @active-evt="handleDrawingActive"
      @editor-evt="handleDrawingEditor"
      @mouse-evt="handleDrawingMouse"
    >
      <template #body="drawingActionInstances"> </template>
    </vc-drawings>

    <el-drawer
      v-model="drawerVisible"
      title="空域设置"
      @closed="handleClose"
      :size="400"
      class="airspace-draw"
    >
      <el-form :model="form">
        <el-form-item label="空域类型" :label-width="120">
          <el-select v-model="form.airspaceType" placeholder="请选择空域类型">
            <el-option
              v-for="item in airSpaceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="空域高度" :label-width="120">
          <el-input-number
            v-model="form.height"
            autocomplete="off"
            placeholder="请输入空域高度"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { VcDrawings } from "vue-cesium";
import { ElMessage } from "element-plus";
import api from "@/api";

const drawings = ref(null);

const drawerVisible = ref(false);
// 空域类型选项
const airSpaceTypes = ref([]);
// 空域图形类型
const airSpaceShapeTypes = ref([]);

// 新增空域数据
const form = reactive({
  points: "",
  height: 0,
  airspaceType: "",
  airspaceShapeType: "",
  region: "NJLH",
});
const SHAPE_MAP = {
  pin: 8,
  point: 9,
  polyline: 10,
  polygon: 11,
  rectangle: 12,
  regular: 13,
  circle: 14,
};
let [cursor, drawing] = [null, null];

const emits = defineEmits(["change"]);

onMounted(async () => {
  await getAirSpaceType();
  await getAirSpaceShapeType();
});

// 获取空域类型
const getAirSpaceType = async () => {
  const result = await api.getAirSpaceType();
  if (result.code === 200) {
    airSpaceTypes.value = result.data || [];
  } else {
    ElMessage.error(result.msg || "服务器忙，请稍后重试！");
  }
};

// 获取空域图形类型
const getAirSpaceShapeType = async () => {
  const result = await api.getAirSpaceShapeType();
  if (result.code === 200) {
    airSpaceShapeTypes.value = result.data || [];
  } else {
    ElMessage.error(result.msg || "服务器忙，请稍后重试！");
  }
};

const handleClose = () => {
  drawerVisible.value = false;
  drawings.value.clearAll();
};

const handleConfirm = async () => {
  const result = await api.saveAirSpace(form);
  if (result.code === 200) {
    ElMessage.success({
      message: result.msg || "保存成功！",
      onClose: () => {
        drawings.value.clearAll();
        drawerVisible.value = false;
        resetForm();
        emits("change", "add", {
          ...result.data,
          points: JSON.parse(result.data.points),
        });
      },
    });
  } else {
    ElMessage.error(result.msg || "服务器忙，请稍后重试！");
  }
};

const resetForm = () => {
  form.points = "";
  form.height = 0;
  form.airspaceType = "";
  form.airspaceShapeType = "";
};

const handleDrawingDraw = (e, viewer) => {
  const restoreCursor = getComputedStyle(viewer.canvas).cursor;
  if (e.finished) {
    if (e.type === "move") {
      viewer.canvas.setAttribute("style", `cursor: ${cursor}`);
    }
    drawing = false;
    form.airspaceShapeType = SHAPE_MAP[e.name];
    if (e.name === "polygon" || e.name === "polyline") {
      form.points = JSON.stringify(
        (e.positionsDegreesArray || []).map((item) => ({
          longitude: item[0],
          latitude: item[1],
        }))
      );
    } else if (e.name === "point" || e.name === "pin") {
      form.points = JSON.stringify({
        longitude: e.positionDegrees[0],
        latitude: e.positionDegrees[1],
      });
    } else {
      form.points = JSON.stringify(
        (e.polygonPositionsDegreesArray || []).map((item) => ({
          longitude: item[0],
          latitude: item[1],
        }))
      );
    }
    drawerVisible.value = true;
  } else {
    drawing = true;
    if (e.type === "move") {
      viewer.canvas.setAttribute("style", "cursor: move");
    }
    if (e.type === "new") {
      viewer.canvas.setAttribute("style", "cursor: crosshair");
    }
  }
};

const handleDrawingActive = (e, viewer) => {
  viewer.canvas.setAttribute(
    "style",
    `cursor: ${e.isActive ? "crosshair" : "auto"}`
  );
  if (!e.isActive) {
    drawing = false;
    cursor = "auto";
  }
};

const handleDrawingEditor = (e, viewer) => {
  if (e.type === "move") {
    viewer.canvas.setAttribute("style", "cursor: move");
    drawing = true;
  } else {
    viewer.canvas.setAttribute("style", "cursor: auto");
  }
};

const handleDrawingMouse = (e, viewer) => {
  const restoreCursor = getComputedStyle(viewer.canvas).cursor;
  if (!drawing) {
    if (e.type === "onmouseover") {
      cursor = restoreCursor;
      viewer.canvas.setAttribute("style", "cursor: pointer");
    } else {
      viewer.canvas.setAttribute("style", `cursor: ${cursor || "auto"}`);
    }
  }
};

// 画空域
const handleDrawingSpace = (type) => {
  drawings.value.toggleAction(type);
};

defineExpose({
  handleDrawingSpace,
});
</script>

<style scoped lang="scss">
::v-deep .airspace-draw {
  background: linear-gradient(
    180deg,
    rgba(8, 40, 75, 0.45) 0%,
    rgba(10, 41, 73, 0.45) 15.35%,
    rgba(11, 70, 146, 0.45) 35.16%,
    rgba(11, 78, 167, 0.45) 62.46%,
    rgba(11, 30, 60, 0.45) 83.98%,
    rgba(13, 33, 58, 0.45) 100%
  ) !important;
  border: 4px solid;
  border-color: rgba(84, 84, 84, 0.45);
  border-radius: 15px;
}
::v-deep .el-drawer__header {
  padding-top: 0 !important;
  padding-right: 0 !important;
}
::v-deep .el-form-item__label {
  width: auto !important;
}
</style>
